package myLearnjdk.jdk.lang.iot;




import java.util.BitSet;

/**
 * 比特操作工具类
 * @Description: 
 * @author  yangcheng
 * @date:   2018年12月3日
 */
public class BitUtil {
	static int[] BITMASKS;

	static {
		int bit = 1;
		BITMASKS = new int[32];
		for (int i = 0; i < 32; i++) {
			BITMASKS[i] = bit;
			bit <<= 1;
		}
	}

	public static boolean readBit(int data, int pos) {
		return (data & BITMASKS[pos]) != 0;
	}

	public static int setBit(int data, int pos) {
		return data | BITMASKS[pos];
	}

	public static int clearBit(int data, int pos) {
		return data & (BITMASKS[pos] ^ 0xFFFFFFFF);
	}

	public static int readBit(int data, int pos, int size) {
		int v = 0;
		int bit = 1;
		for (int i = 0; i < size; i++) {
			if ((data & BITMASKS[(pos + i)]) != 0) {
				v |= bit;
			}
			bit <<= 1;
		}
		return v;
	}

	public static int write(int data, int pos, int size, int v) {
		for (int i = 0; i < size; i++) {
			if ((v & BITMASKS[i]) != 0)
				data = setBit(data, pos + i);
			else {
				data = clearBit(data, pos + i);
			}
		}
		return data;
	}

	public static BitSet toBitSet(int data) {
		BitSet s = new BitSet();
		for (int i = 0; i < 32; i++) {
			if ((data & BITMASKS[i]) != 0) {
				s.set(i);
			}
		}
		return s;
	}

	public static int countSize(BitSet bs) {
		int size = 0;
		for (int i = 0; i < bs.length(); i++) {
			if (bs.get(i))
				size++;
		}
		return size;
	}
	
	public static ByteDataBuffer cleanBuf(ByteDataBuffer oriBuf) {
		ByteDataBuffer newBuf = null;
		byte[] bytes = oriBuf.getBytes();
		String cyphForm = StringUtils.encodeHex(bytes);
		while(cyphForm.startsWith("FE")) {
			cyphForm = clearFE(cyphForm);
		}
		byte[] newBytes = StringUtils.decodeHex(cyphForm);
		newBuf = new ByteDataBuffer(newBytes);
		return newBuf;
	}
	
	public static String cleanBufStr(String cypher) {
		while(cypher.startsWith("FE")) {
			cypher = clearFE(cypher);
		}
		return cypher;
	}
	
	private static String clearFE(String cyph) {
		if(cyph.startsWith("FE")) {
			cyph = cyph.substring(2, cyph.length());
		}
		return cyph;
	}
}
